<?php

namespace App\Http\Controllers;

use App\Http\Requests\RoleStroeRequest;
use App\Models\Role;
use App\Models\UserRole;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

class RoleController extends Controller
{
    /** 角色列表
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function index(Request $request): \Illuminate\Http\JsonResponse
    {
        $roles = new Role();
        $roles  = $roles->index($request);
        return response()->json(['data' => $roles]);
    }

    /** 新增角色
     * @param RoleStroeRequest $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function store(RoleStroeRequest $request): \Illuminate\Http\JsonResponse
    {
        $data = $request->only(['name', 'status', 'description']);
        Role::create($data);
        return response()->json(['message' => '新增角色成功']);
    }

    /** 查看角色详情
     * @param $id
     * @return \Illuminate\Http\JsonResponse
     */
    public function show($id): \Illuminate\Http\JsonResponse
    {
        $role = Role::find($id);
        return response()->json(['data' => $role]);
    }

    /** 更新角色
     * @param Request $request
     * @param $id
     * @return \Illuminate\Http\JsonResponse
     */
    public function update(Request $request, $id): \Illuminate\Http\JsonResponse
    {
        $role = Role::find($id);
        $role->update($request->only(['name', 'description']));
        return response()->json(['message' => '更新角色成功']);
    }

    /**
     * 删除角色
     * @param $id
     * @return \Illuminate\Http\JsonResponse
     */
    public function destroy($id): \Illuminate\Http\JsonResponse
    {
        if (UserRole::where('role_id', $id)->count() > 0) {
            return response()->json(['message' => '该角色下有用户，无法删除']);
        }
        Role::destroy($id);
        return response()->json(['message' => '删除角色成功']);
    }

    /**
     * 角色授权
     * @param Request $request
     * @param $id
     * @return JsonResponse
     */
    public function node(Request $request, $id): \Illuminate\Http\JsonResponse
    {
        $role = Role::find($id);
        $role->nodes()->sync($request->input('nodeIds'));
        return response()->json(['message' => '角色授权成功']);
    }


}
